package quick.portal.fragment.email;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.squareup.okhttp.Request;

import quick.common.AppContext;
import quick.common.UIHelper;
import quick.communication.AsyncHttpResponseHandler;
import quick.portal.R;
import quick.portal.activity.WebviewActivity;
import quick.portal.data.EmailInfo;
import quick.portal.data.ResultMessage;
import quick.portal.fragment.DataListFragment;
import quick.portal.service.BaseService;
import quick.portal.service.EmailInfoService;
import quick.view.quickadapter.BaseAdapterHelper;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.PopupMenu;
import android.widget.TextView;


public class EmailDustbinFragment extends DataListFragment<EmailInfo> {
	
	private List<String> checkedIds = new ArrayList<String>();
	
	public EmailDustbinFragment()
	{
		this.queryAction = "DustbinEmailList";
    	this.itemViewLayoutId = R.layout.data_list_item_email_dustbin;
	}
	
	@Override
	protected void adapterConvert(BaseAdapterHelper helper, EmailInfo mail) {

		String id = mail.getType() + "|" + mail.getId();
		
		helper.setText(R.id.title, mail.getTitle())
        .setTag(R.id.title, mail)
        .setTag(R.id.cbxMail, id)
        .setText(R.id.fromUserName, "发件人：" + mail.getFromUserName())
        .setText(R.id.toUserName, "收件人：" + mail.getToUserName())
        .setText(R.id.sendTime, mail.getSendTime());
		
	}
	
	@Override
	protected void showDetail(View view) {

		TextView tvTitle = (TextView)view.findViewById(R.id.title);
		EmailInfo mail = (EmailInfo)tvTitle.getTag();

		String url = BaseService.getPortalUrl();
		
		if(mail.getType().equals("MySendEmail"))
		{
			url = url + "Systems/MySendEmail/SendEmailDetail/" + mail.getId() + "/";
		}
		else
		{
			url = url + "Systems/MyReceiveEmail/Read/" + mail.getId() + "/";
		}
		
		String token = AppContext.getInstance().getToken();
    	url = url + "?" + AppContext.Login_Token_Key + "=" + token;

        Intent intent = new Intent(context,WebviewActivity.class);
        intent.putExtra("Url", url);
        startActivity(intent);
        
	}
	
	@Override
	protected List<EmailInfo> parseArray(String body) {
		List<EmailInfo> list = JSONArray.parseArray(body, EmailInfo.class);
		
		return list;
	}
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		
		if(isVisibleToUser)
		{
			PopupMenu menu = this.GetOriginalPopupMenu();
			menu.getMenu().add(R.id.menu_group_data,R.id.menu_restore_dustbin_email,menu.getMenu().size(),"恢复邮件");
			menu.getMenu().add(R.id.menu_group_data,R.id.menu_delete_dustbin_email,menu.getMenu().size(),"彻底删除");
			menu.setOnMenuItemClickListener(this);
		}
	}

	@Override
	protected void initItemView(View view)
	{
		CheckBox cbxMail = (CheckBox)view.findViewById(R.id.cbxMail);
		cbxMail.setOnClickListener(new View.OnClickListener() {  
            
            @Override  
            public void onClick(View v) {
                CheckBox cb = (CheckBox)v;
                String id = cb.getTag().toString();
                
                if(cb.isChecked())
                {
                	checkedIds.add(id);
                }
                else
                {
                	checkedIds.remove(id);
                }
            }  
        }); 
	}
	
	@Override
	public boolean onMenuItemClick(MenuItem item) {
		super.onMenuItemClick(item);
		
	    if (item.getItemId() == R.id.menu_delete_dustbin_email) {
	    	
	    	if(this.checkedIds.size()<=0)
	    	{
	    		UIHelper.ToastMessage(context, "请选择要删除的邮件");
	    		return true;
	    	}
	    	
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
			
			builder.setTitle(R.string.app_name);
			builder.setMessage("删除之后不可恢复，确定要删除吗?");
			
			builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					deleteDustbinEmail();
				}
			});
			
			builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			});
			
			builder.create().show();
	    	
	    	return true;
	    }
	    
	    if (item.getItemId() == R.id.menu_restore_dustbin_email) {
	    	
	    	if(this.checkedIds.size()<=0)
	    	{
	    		UIHelper.ToastMessage(context, "请选择要恢复的邮件");
	    		return true;
	    	}
	    	
	    	this.restoreEmail();
	    	
	    	return true;
	    }
	    
	    return false;
	}
	
	private String getIds()
	{
		String ids = "";
		
    	for(int i=0;i<this.checkedIds.size();i++)
    	{
    		if(i<this.checkedIds.size()-1)
    		{
    			ids = ids + this.checkedIds.get(i) + ",";
    		}
    		else
    		{
    			ids = ids + this.checkedIds.get(i);
    		}
    	}
    	
    	return ids;
	}
	
	private void restoreEmail()
	{
		String ids = this.getIds();

		new EmailInfoService().restoreDustbinEmail(ids, new AsyncHttpResponseHandler() {
			
			@Override
            public void onSuccess(String body) {

				ResultMessage result = JSON.parseObject(body, ResultMessage.class);
				
				if(result.getSuccess())
				{
					refreshData();
				}
				
				UIHelper.ToastMessage(context,result.getMessage());
			}
			
			@Override
            public void onFailure(Request request, IOException e) {
                UIHelper.ToastMessage(context, "恢复失败：" + e.getMessage());
            }

		});
	}
	
	private void deleteDustbinEmail()
	{
		String ids = this.getIds();
		
		new EmailInfoService().DeleteDustbinEmail(ids, new AsyncHttpResponseHandler() {
			
			@Override
            public void onSuccess(String body) {

				ResultMessage result = JSON.parseObject(body, ResultMessage.class);
				
				if(result.getSuccess())
				{
					refreshData();
				}
				
				UIHelper.ToastMessage(context,result.getMessage());
			}
			
			@Override
            public void onFailure(Request request, IOException e) {
                UIHelper.ToastMessage(context, "删除失败：" + e.getMessage());
            }

		});
	}
	
}